<template>
  <div class="books">
    <top-swiper :hotList="hotList" />
    <card :books="bookList"></card>
    <p class="text-footer" v-show="nomore">没有更多数据了哦🚫</p>
  </div>
</template>

<script>
import Card from '@/components/card.vue'
import TopSwiper from '@/components/TopSwiper.vue'
import { checkOk, showMod } from '@/utils/index.js'

const db = wx.cloud.database()

export default {
  name: 'Books',
  data () {
    return {
      bookList: [],
      hotList: [],
      page: 0, // 当前页
      limit: 7, // 每次拿到 10 个数据
      nomore: false
    }
  },
  methods: {
    async _getBookList (init) { // 获取十条数据  limit skip
      wx.showNavigationBarLoading() // 在当前页面显示导航条加载动画
      if (this.bookList.length < this.limit * this.page && this.page > 0) { // 没有更多
        this.nomore = true
      }
      if (init) {
        this.page = 0
        this.nomore = false
        // 不使用 skip
        await db.collection('books')
          .limit(this.limit)
          .get()
          .then(res => {
            if (checkOk(res.errMsg)) {
              this.bookList = res.data
            } else {
              showMod({title: '错误', content: '数据获取失败'})
            }
          })
      } else {
        await db.collection('books')
          .skip(this.limit * this.page) // skip 不能为0 下版本修复？？？
          .limit(this.limit)
          .get()
          .then(res => {
            if (checkOk(res.errMsg)) {
              // 下拉刷新， 累加bookList
              this.bookList = [...this.bookList, ...res.data]
            } else {
              showMod({title: '错误', content: '数据获取失败'})
            }
          })
      }
      wx.stopPullDownRefresh()
      wx.hideNavigationBarLoading() // 在当前页面隐藏导航条加载动画
    },
    async _getHotList () { // 获取热门书籍
      await wx.cloud.callFunction({
        name: 'hotList'
      })
        .then(res => {
          this.hotList = res.result.data
        })
        .catch(err => console.error(err))
    }
  },

  mounted () {
    this._getBookList(true)
    this._getHotList()
  },
  onPullDownRefresh () {
    this._getBookList(true)
  },
  onReachBottom () { // 上拉加载更多
    if (this.nomore) {
      // 没有更多
      return false
    }
    this.page++
    this._getBookList()
  },
  components: {
    Card,
    TopSwiper
  }
}
</script>

<style lang="stylus" scoped>
</style>
